package com.xinhe.web.interceptor;

import com.xinhe.web.session.UserSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Slf4j
public class SessionInterceptor extends HandlerInterceptorAdapter {

    private String[] unValidateStr = null;
    private UserSessionManager userSessionManager;

    public SessionInterceptor(UserSessionManager userSessionManager, String[] unValidateStr) {
        this.userSessionManager = userSessionManager;
        this.unValidateStr = unValidateStr;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (true){
            return true;
        }
        if ("options".equalsIgnoreCase(request.getMethod())) {
            return super.preHandle(request, response, handler);
        }
        String requestUrl = request.getRequestURI();
        //log.debug(ClientIpUtil.getClientIp(request) + requestUrl);
        String token = request.getHeader("x-access-token");
        log.info("header:x-access-token={}", token);
        //如果请求url不是免token校验请求，则进行token校验
        if (!isUnValidateUrl(requestUrl)) {
            if (!this.userSessionManager.validToken()) {
                log.info("no_user: requestUrl={}, token={}", requestUrl, token);
                //write(response, "{\"errors\":[],\"msg\":\"no_user\",\"success\":false}");
                return false;
            }  if (!this.userSessionManager.validMenu(requestUrl)) {
                log.info("no_menu: requestUrl={}, token={}", requestUrl, token);
                //write(response, "{\"errors\":[],\"msg\":\"no_menu\",\"success\":false}");
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }
    //判断请求url是否是免token校验请求
    private boolean isUnValidateUrl(String requestUrl) {
        Boolean flag = false;
        for (String str : this.unValidateStr) {
            if (requestUrl.toLowerCase().contains(str.toLowerCase())) {
                flag = true;
                break;
            }
        }
        return flag;
    }


    public SessionInterceptor() {}
    public String[] getUnValidateStr() {
        return this.unValidateStr;
    }
    public void setUnValidateStr(String[] unValidateStr) {
        this.unValidateStr = unValidateStr;
    }


    private void write(HttpServletResponse response, String result) {
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e1) {
            log.error(e1.getMessage(), e1);
        }
    }

}
